<?php
namespace Home\Controller;
use Think\Controller;

class PayWController extends CommonController {

     /**
      * 生成支付代码
      * @param   array   $order      订单信息
      * @param   array   $payment    支付方式信息
      */
    public function wx_pay() 
    {
        $order_id = I("post.order_id");
        $order = M("order")->where("order_id = %s AND uid = %d" ,array($order_id ,session("user_id")))->find();
        if($order)
        {
            $wxpay_ment = M("payment")->where("pay_code = 'wxpay'")->find();
            $payment = unserialize($wxpay_ment['p_conf']);
            $order_amt = ($order['price']* 100 - $order['discount'] *100) / 100; // 注意订单金额
    //        微信商户相关信息
            $appid = $payment['appid'];
            $mch_id = $payment['mchid'];
            $key = $payment['key'];
    //        商品描述（商品名称）
            $body = $order['order_id'];
    //        商户订单号
            $out_trade_no = $order['order_id'];
    //        MD5加密订单号生成的随机字符串
            $nonce_str = MD5($out_trade_no);
    //        订单金额
            $total_fee = $order_amt * 100;
    //        通知地址
            $notify_url = 'http://cxl.tangjunshen.com/wxpay/notify_url';
    //        终端IP
            $spbill_create_ip = get_client_ip();
    //       交易类型
//            $trade_type = 'MWEB';
            $trade_type = 'JSAPI'; // 必需要加上 openid
            $openid = "oJdjzvltYk04wXRWW7sexIuie840";
    //        场景信息（wap_url为wap网站url地址）
//            $scene_info = '{"h5_info": {"type":"Wap","wap_url": "http://cxl.tangjunshen.com/","wap_name": "微联盟"}}';
    //        生成签名
            $signA = "appid=$appid&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_url=$notify_url&out_trade_no=$out_trade_no&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type&openid=$openid";
            $strSignTmp = $signA."&key=$key";
            $sign = strtoupper(MD5($strSignTmp));
    //        组装xml
            $post_data = "<xml>
                            <appid>$appid</appid>
                            <body>$body</body>
                            <mch_id>$mch_id</mch_id>
                            <nonce_str>$nonce_str</nonce_str>
                            <notify_url>$notify_url</notify_url>
                            <out_trade_no>$out_trade_no</out_trade_no>
                            <spbill_create_ip>$spbill_create_ip</spbill_create_ip>
                            <total_fee>$total_fee</total_fee>
                            <openid>$openid</openid>
                            <trade_type>$trade_type</trade_type>
                            <sign>$sign</sign>
                        </xml>";//拼接成XML 格式

            $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//统一下单接口
            $dataxml = $this->http_request($url, $post_data); //后台POST统一下单接口  同时取得微信返回的参数
            $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //将微信返回的XML 转换成数组
            // mweb_url就是微信返回的支付链接
//            $mweb_url = $objectxml['mweb_url'];
//            $button = '<div style="text-align:center"><a href="'.$mweb_url.'" style="background:#FF591F;border:1px solid #FF591F;color:#fff;padding:3px 10px;border-radius:3px;">手机微信支付</a></div>';
//            // return $button;
            print_r($objectxml);
            echo $objectxml['code_url'];exit;
            header('Location: '.$objectxml['mweb_url']);
        }else{
            $this->error("支付失败");
        }
    }

    protected function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    // 微信支付异步通知地址
    public function wxpay_notify()
    {
        @file_put_contents("./a.log", 123123 ."\n" ,FILE_APPEND);
        $input = file_get_contents('php://input');
        if (!empty($input)) {
            if (preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $input)) {
                exit('fail');
            }

            libxml_disable_entity_loader(true);
            $obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
            @file_put_contents("./a.log", json_encode($obj) ,FILE_APPEND);
            $data = json_decode(json_encode($obj), true);

            if (empty($data)) {
                exit('fail');
            }

            if ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS') {
                exit('fail');
            }else{
                M('order')->where( array('order_id' => $data['out_trade_no']) )->save( array('is_pay' => 1,'pay_type'=>1) );
            }
        }
    }
}